package com.example.customcondition.config;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 获得注解@ConditionalOnLinux的所有属性
        List<AnnotationAttributes> allAnnotationAttributes = annotationAttributesFromMultiValueMap(Objects.requireNonNull(metadata.getAllAnnotationAttributes(ConditionalOnLinux.class.getName())));
        for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) {
            // 获得注解@ConditionalOnLinux的environment属性
            String environment = annotationAttributes.getString("environment");
            // 若environment等于linux，则返回true
            if ("linux".equals(environment)) {
                return true;
            }
        }
        return false;
    }

    private List<AnnotationAttributes> annotationAttributesFromMultiValueMap(MultiValueMap<String, Object> allAnnotationAttributes) {
        ArrayList<AnnotationAttributes> annotationAttributes = new ArrayList<>();
        for (String s : allAnnotationAttributes.keySet()) {
            List<Object> objects = allAnnotationAttributes.get(s);
            annotationAttributes.add((AnnotationAttributes) objects);
        }
        return annotationAttributes;
    }
}
